<template>
  <div class="app-container customer-div">
    <div style="font-size:12px;color:red;line-height: 20px">
      公海池： 客户使用塑料原料，未使用公司主营塑料原料
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
          <el-form-item label="客户名称：">
            <el-autocomplete
              clearable
              class="inline-input"
              value-key="customerName"
              :fetch-suggestions="querySearch"
              v-model="listQuery.customerName"
              placeholder="请输入内容"
              @select="handleSelectCustomerName"
              :trigger-on-focus="false"
            ></el-autocomplete>
          </el-form-item>

          <el-form-item label="最近成交时间：">
            <el-date-picker
              v-model="listQuery.lastOrderTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="是否成交：">
            <el-select v-model="listQuery.isOrder" filterable placeholder="请选择" clearable>
              <el-option label="已成交" :value="1"></el-option>
              <el-option label="未成交" :value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="客户等级：">
            <el-select v-model="listQuery.newLevel" class="input-width" style="width:250px" placeholder="请选择" clearable>
              <el-option
                v-for="(item,index) in customerLevelList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所在地区：">
            <el-select v-model="listQuery.areaId1" placeholder="请选择省" @change="changeAreaId1" style="width:120px" clearable>
              <el-option v-for="item in areaList"  :key="item.areaId" :label="item.areaName"  :value="item.areaId" ></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-if="listQuery.areaId1" style="width:120px" clearable>
              <el-option v-for="item in areaList[areaIndex1]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-else style="width:120px" clearable></el-select>
            <el-select v-model="listQuery.areaId3" placeholder="请选择区" style="width:120px" v-if="listQuery.areaId2" clearable>
              <el-option v-for="item in areaList[areaIndex1]['areaChildList'][areaIndex2]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId3" placeholder="请选择区" v-else style="width:120px"></el-select>
          </el-form-item>

           <el-form-item label="创建时间：">
            <el-date-picker
              v-model="listQuery.customerCreateTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="最近流入时间：">
            <el-date-picker
              v-model="listQuery.chargeStartTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

<!--          <el-form-item label="产品线：">-->
<!--            <el-select v-model="listQuery.goodsLineId" filterable clearable>-->
<!--              <el-option-->
<!--                v-for="(item,index) in goodsLineList"-->
<!--                :key="index"-->
<!--                :label="item.cddValue"-->
<!--                :value="item.cddId">-->
<!--             </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        <el-form-item label="品类：">
          <el-cascader
            filterable
            :options="categoryList" clearable v-model="listQuery.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
        </el-form-item>

          <el-form-item label="客户性质：">
            <el-select v-model="listQuery.customerQuality" clearable>
              <el-option v-for="item in customerQualityList"  :key="item.cddId"  :value="item.cddId" :label="item.cddValue"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="吨毛利标红过滤：" label-width="120px">
          <el-select v-model="listQuery.isSaleProfit" clearable>
            <el-option value="1" label="是"></el-option>
            <el-option value="0" label="否"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="月销量标红过滤："  label-width="120px">
          <el-select v-model="listQuery.isShipNum" clearable>
            <el-option value="1" label="是"></el-option>
            <el-option value="0" label="否"></el-option>
          </el-select>
        </el-form-item>

          <el-form-item>
            <el-button @click="handleSearchList()" type="primary">查询</el-button>
            <el-button v-if="isCanCustomerByImport" @click="showImport()">导入</el-button>
        </el-form-item>
      </el-form>
    </div>
  <div class="table-container">
    <el-table
      @selection-change="handleSelectionChange"
      v-loading="listLoading"
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px">
      <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
      <el-table-column
        fixed
        align="center"
        label="客户名称"
        width="200">
        <template slot-scope="scope">
          <el-link @click="toDetail(scope.row)" type="primary"  style="font-size:12px">
            {{scope.row.customerName}}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="子客户"
        align="center"
        width="200">
        <template slot-scope="{row}">
          <div v-for="(item,index) in row.sonName" :key="index">
            {{ item }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="aboutPerProfit" label="吨毛利" align="center" width="100">
        <template slot-scope="{row}">
          <span :style="{'color':row.isSaleProfit == 1 ? 'red' :'#606266'}">{{row.aboutPerProfit}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="aboutBuyNum" label="月销量" align="center" width="100">
        <template slot-scope="{row}">
          <span :style="{'color':row.isShipNum == 1 ? 'red' :'#606266'}">{{row.aboutBuyNum}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="saleProfit" label="前6月均吨毛利" align="center" width="150"></el-table-column>
      <el-table-column prop="shipNum" label="前6月均销量" align="center" width="150"></el-table-column>
      <el-table-column prop="goodsLineNames" label="产品线" align="center" width="150"></el-table-column>
      <el-table-column prop="noChargeReason" label="流入公海原因" align="center" width="150"></el-table-column>
      <el-table-column prop="stepName" label="开发阶段" align="center" width="100"></el-table-column>
      <el-table-column prop="customerNewType" label="客户分类" align="center" width="100"></el-table-column>
      <el-table-column prop="newNature" label="规模性质" align="center" width="100"></el-table-column>
      <el-table-column prop="customerQualityStr" label="客户性质" align="center" width="100"></el-table-column>
      <el-table-column prop="newLevel" label="客户级别" align="center" width="100"></el-table-column>
      <el-table-column prop="lastTrackingTime" label="最近跟进时间" align="center" width="130"></el-table-column>
      <el-table-column prop="lastVisitTime" label="最近拜访时间" align="center" width="130"></el-table-column>
      <el-table-column prop="lastOrderTime" label="最近成交时间" align="center" width="130"></el-table-column>
      <el-table-column prop="inquiryPriceCount" label="本月询盘次数" align="center" width="110"></el-table-column>
      <el-table-column
        width="150"
        fixed="right"
        label="操作"
        align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="toDetail(scope.row)">查看
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="showQuit(scope.row,'one')">转移
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="pagination-container">
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes,prev, pager, next,jumper"
      :current-page.sync="listQuery.pageNum"
      :page-size="listQuery.pageSize"
      :page-sizes="[10,15,20]"
      :total="count">
    </el-pagination>
  </div>

    <!--批量导入-->
    <el-dialog
      :show-close="showClose"
      :close-on-click-modal="showClose"
      :close-on-press-escape="showClose"
      :title="poptitle"
      :beforeClose="beforeCloseEditPrice"
      :visible.sync="dialogVisibleImprot"
      width="500px">
      <div>
        <el-alert
          title="请先下载模板，维护后，再上传更新后的模板文件"
          type="warning"
          :closable="false">
        </el-alert>
        <div style="text-align: center;padding:20px;padding-bottom:10px">
          <el-link :href="url" type="primary" :underline="false">下载模板</el-link>
        </div>
        <div class="upload-div">
          <input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
          <el-button type="primary" size="small" :loading="uploadLoading">选择上传文件</el-button>
        </div>
        <div style="margin:20px auto;margin-bottom:0;word-break:break-all;text-align: left;line-height:20px;background: #fef0f0;color:#f56c6c;padding:10px" v-if="msg!=''">
          <div style="max-height: 90px;overflow: auto;padding:10px"><div v-if="showFial">添加失败：</div>{{msg}}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEditPriceConfirm" :loading="EditLoading">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 转移 -->
    <cmsTransfer ref='cmsTransfer' @update="getUserList"></cmsTransfer>

  </div>
</template>
<script>
import {
  importCustomer,
  importBatchMove,
  getCustomerSetting,
  getCustomerOption,
  setCustomerMove,
} from '@/api/partner';
import {
 commonList
} from '@/api/company';
import { mapGetters } from 'vuex';
import store from '@/store';
import { formatDate } from '@/utils/date';
import { getStaffsList } from '@/api/management';
import { getToken } from '@/utils/auth';
import cmsTransfer from '@/views/cms/components/cmsTransfer.vue';
const defaultListQuery={
  pageNum: 1,
  pageSize: 10,
  type:'',
  tab: '',
  isToday:0,
  lastTrackingTime: null,
  lastOrderTime:null,
  customerName:null,
  userId: null,
  isOrder:null,
  notTrackingTime:'',
  newLevel:'',
  isEndMonth: '',//是否临近宽带
  areaId1: '',//省ID
  areaId2: '',//市
  areaId3: '',//区
  customerCreateTime:[],//创建时间
  chargeStartTime: [],//负责时间搜索
  goodsLineId:'',//产品线ID搜索
  contactMobile: '',//联系人的电话搜索
  customerQuality:'',//客户性质
  categoryId:'',
  isSaleProfit:'',
  isShipNum:''
};
export default {
  name: "publicList",
  props: {
    areaList: {
      type: Array,
      default:()=>[]
    },
    customerLevelList:{
      type: Array,
      default:()=>[]
    },
    goodsLineList: {
      type: Array,
      default:()=>[]
    },
    userOptionList:{
      type: Array,
      default:()=>[]
    },
    customerQualityList: {
      type: Array,
      default:()=>[]
    },
    categoryList: {
      type: Array,
      default:()=>[]
    },
  },
  data(){
    return {
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      da:[],
      file:null,
      dialogVisibleImprot:false,//批量导入弹窗
      EditLoading:false,//批量导入提交按钮loadin
      showFial:false,//批量导入失败
      msg: '',//上传文件信息
      uploadLoading: false,
      multipleSelection: [],
      list2: [],
      quitForm:{
        target:'',
        remark:'',
      },
      itemQuit: {},
      dialogVisible3: false,
      btnLoading3: false,
      tableData: [],
      count: 0,
      listLoading: false,
      // customerDegreeList: [],
      // customerSourceList: [],
      // customerTypeList: [],
      // customerStateList: [],
      areaId1:'',
      areaId2:'',
      areaId3: '',
      showClose: true,
      poptitle: '',
      url: '',
      quitRules:{
        remark:[{required: true, message: '请输入转移备注', trigger: 'blur'},],
      },
      areaIndex1:null,
      areaIndex2: null,
      token: '',
      importType:'',
      hasCustomerType: null,
      hasAgreement:null,
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    isCanCustomerByImport(){
      if(this.roles.indexOf("customerByImport") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.token = getToken();
    this.url = '/api/customers/template/download?token=' + this.token;
  },
  filters: {
    fifTypeList(val){
      if(val == 'isBlackList'){
        return  '黑名单'
      }else if(val == 'isDelete'){
        return  '回收站'
      }else if(val == 'noCharge'){
        return  '公海'
      }else if(val == 'normal'){
        return  '正常'
      }else if(val == 'isBlackListApply'){
        return  '黑名单待审'
      }else if(val == 'isDeleteApply'){
        return  '回收站待审'
      }else if(val == 'outNoCharge'){
        return  '领取客户待审'
      }else if(val == 'moveCharge'){
        return  '转移客户待审核'
      }
    },
    formatCreateTime(time) {
      if(time){
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }else{
        return '--'
      }
    },
    filterIsChina(val){
      if(val== 2){
        return '外贸'
      } else if(val == 1){
        return '国内'
      }
    },
  },
  components: {
    cmsTransfer
  },
  methods: {
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getUserList();
    },
    init(tab, type) {
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
      this.listQuery.tab = tab;
      this.listQuery.type = type;
      this.getUserList();
    },
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
      window.open(routeData.href);
    },
    //切换省
    changeAreaId1(item) {
        this.areaIndex1 = this.areaList.findIndex((el)=>{
          return item == el.areaId
        });
        this.areaIndex2 = null;
        this.listQuery.areaId2 = '';
        this.listQuery.areaId3 = '';
    },
    //切换市
    changeAreaId2(item){
      this.areaIndex2 = this.areaList[this.areaIndex1]['areaChildList'].findIndex((el)=>{
        return item == el.areaId
      });
      this.listQuery.areaId3 = '';
    },
    //客户名称输入匹配
    querySearch(queryString, cb){
      getCustomerOption({keywords:queryString}).then((res)=>{
        cb(res);
      })
    },

    //选择客户名称
    handleSelectCustomerName(item){
      this.listQuery.customerName = item.customerName
    },
    //关闭转移弹窗
    handleClose3(){
      this.dialogVisible3 = false;
      this.btnLoading3 = false;
      this.quitForm.target = '';
    },

    //确认转移
    handleConfirm3(){
      this.$refs.quitForm.validate((valid) => {
        if (valid) {
          let ids=[];
          for(let i=0;i<this.multipleSelection.length;i++){
            ids.push(this.multipleSelection[i].customerId);
          }
          this.btnLoading3 = true;
          let data = {};
          data.customerIds = ids;
          data.target = this.quitForm.target;
          data.remark = this.quitForm.remark;
          setCustomerMove(data).then((res)=>{
            this.btnLoading3 = false;
            this.handleClose3();
            this.getUserList();
          }).catch(()=>{
            this.btnLoading3 = false;
          })
        }
      })
    },
     //显示转移弹窗  列表接口缺少isCharge字段
    showQuit(row, type) {
      this.$refs.cmsTransfer.showPop(row.customerId,type,row.isCharge);
    },
    //多选表格项
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //获取客户列表
    getUserList() {
      this.listLoading = true;
      commonList(this.listQuery).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },
    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getUserList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getUserList();
    },
    //显示批量导入弹窗
    showImport(type){
      this.showFial = false;
      this.EditLoading = false;
      this.uploadLoading = false;
      this.msg = '';
      this.dialogVisibleImprot = true;
      if(type){
          this.poptitle = '批量客户转移';
          this.url = '/api/customers/template/download?type=importBatchMove&token=' + this.token;
          this.importType = 'zuanyi'
      }else{
        this.poptitle = '批量导入客户';
        this.url = '/api/customers/template/download?token=' + this.token;
        this.importType = 'kehu'
      }
    },
    //关闭批量导入弹窗
    beforeCloseEditPrice(){
        $("#upload").val('');
        this.da = [];
        this.msg = '';
        this.dialogVisibleImprot = false;
    },
    //提交批量导入
    handleEditPriceConfirm(){
      if (this.da.length == 0){
        this.$message({
          message: '上传数据为空',
          type: 'warning'
      });
        return false;
      }
      this.msg = '后台处理中，请耐心等待……';
      this.showFial = false;
      this.EditLoading = true;
      this.showClose = false;
      let fn;
      fn = this.importType == 'kehu' ? importCustomer : importBatchMove;
      fn({list:this.da}).then((res)=>{
          this.$message({
              message: '修改成功',
              type: 'success'
          });
          this.msg = '修改成功';
          if(res.content != ''){
            this.msg = res.content;
          }
          this.EditLoading = false;
          this.dialogVisible = false;
          this.showClose = true;
          this.da = [];
          this.dialogVisibleImprot = false;
          $("#upload").val('');
          this.getUserList();
      }).catch((err)=>{
          this.msg = err.msg;
          this.showFial = true;
          this.EditLoading = false;
          $("#upload").val('');
          this.showClose = true;
      })
    },
    //导入excel
    importfxx(obj) {
      let _this = this;
      this.uploadLoading = true;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function(e) {
              var bytes = new Uint8Array(reader.result);
              var length = bytes.byteLength;
              for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
              }
              var XLSX = require('xlsx');
              if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                      type: 'base64'
                  });
              } else {
                  wb = XLSX.read(binary, {
                      type: 'binary'
                  });
              }
              outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
              _this.da = [...outdata];
              let arr = [];
              let para = {
                  withList: arr
              };
              _this.$message({
                  message: '上传成功，请点击提交',
                  type: 'success'
              });
              _this.uploadLoading = false;
          };
          reader.readAsArrayBuffer(f);
      };
      if(rABS) {
          reader.readAsArrayBuffer(f);
      } else {
          reader.readAsBinaryString(f);
      }
    },
  },
}
</script>
<style scoped lang="scss">
.upload-div{
    text-align: center;
    position:relative;
    #upload{
      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
</style>



